package com.wpzf.ndhc.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wpzf.common.core.utils.ServletUtils;
import com.wpzf.common.core.web.domain.AjaxResult;
import com.wpzf.common.log.annotation.Log;
import com.wpzf.common.log.enums.BusinessType;
import com.wpzf.common.security.service.TokenService;
import com.wpzf.ndhc.mapper.WpSjsbNdDTOMapper;
import com.wpzf.ndhc.service.WpzfDbCheckService;
import com.wpzf.ndhc.utils.CheckUtil;
import com.wpzf.ndhc.utils.DBUtil;
import com.wpzf.ndhc.utils.GTYUtil;
import com.wpzf.ndhc.utils.LogUtil;
import com.wpzf.system.api.model.LoginUser;
import com.wpzf.zxhc.mapper.WpzfDockMapper;
import com.wpzf.zxhc.service.WpzfDockService;
import com.wpzf.zxhc.service.impl.WpzfDockServiceImpl;
import com.wpzf.zxhc.utils.OBSUploadUnits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/wpzfndhcdb")
public class WpzfDbCheckController {

    @Value("${exepath}")
    public String exePath;

    private DBUtil dbUtil = new DBUtil();
    private CheckUtil checkUtil = new CheckUtil();

    private GTYUtil gtyUtil = new GTYUtil();

    @Autowired
    WpzfDockService wpzfDockGxServiceImpl;
    @Autowired
    WpSjsbNdDTOMapper wpSjsbNdDTOMapper;

    @Autowired
    TokenService tokenService;

    @Autowired
    WpzfDbCheckService wpzfDbCheckServiceImpl;

    @Autowired
    WpzfDockMapper wpzfDockMapper;

    private final static ResourceBundle rb2 = ResourceBundle.getBundle("config/log");
    private final static String logUrl = rb2.getString("logToTxtUrl.ndSj.pushDb");
    @Autowired
    private WpzfDockServiceImpl wpzfDockServiceImpl;


    @Log(title = "DB生成质检提交到国土云", businessType = BusinessType.OTHER)
    @RequestMapping(value = "/pushDB", method = RequestMethod.POST)
    public AjaxResult pushDB(@RequestBody Map<String, Object> param) throws IOException {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String user_xzqdm = loginUser.getSysUser().getXzqdm();
        String xzqdm = param.get("xzqdm") + "";
        if (user_xzqdm.equals(xzqdm.substring(0, 2))) {
            String savePath = System.getProperty("user.dir") + "\\" + "pushDBFile";
            File folder = new File(savePath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            //从表中获取
            List<Map<String, Object>> restList = wpzfDockGxServiceImpl.queryAllQualitytestingByXzqdm(param);
            for (Map<String, Object> rest : restList) {
                LogUtil.logToTxt(xzqdm + "打包质检结果：" + rest, logUrl);
                if (rest != null) {
                    if (rest.get("dburl") == null || rest.get("dburl").toString() == "") {
                        return AjaxResult.error("该区县DB包暂未打包，无法提交");
                    }
                    String dbPath = rest.get("dburl").toString();
                    String dbPass = rest.get("dbpassword").toString();
                    String status = rest.get("status").toString();//已质检状态
                    String updatestatus = rest.get("updatestatus").toString();//更新状态
                    String submitstatus = rest.get("submitstatus").toString();//提交状态
                    xzqdm = rest.get("xzqdm").toString();

                    if (("0").equals(updatestatus))  //无更新
                    {
                        if (("2").equals(status)) //已质检
                        {
                            if (!Objects.equals(rest.get("signurl").toString(), "") && rest.get("signurl") != null) //质检通过 产生签章
                            {
                                String fileName = dbPath.substring(dbPath.lastIndexOf("/") + 1);
                                dbPath = downloadByIO(dbPath, savePath, fileName);
                                File dbfile = new File(dbPath);

                                String signpath = rest.get("signurl").toString();
                                fileName = signpath.substring(signpath.lastIndexOf("/") + 1);
                                signpath = downloadByIO(signpath, savePath, fileName);
                                String fileContent = "";
                                File signfile = new File(signpath);
                                if (signfile.exists()) {
                                    LogUtil.logToTxt("签章下载成功", logUrl);
                                    fileContent = readFileAsString(signpath);
                                }

                                JSONObject obj = JSON.parseObject(fileContent);
                                //获取到上传路径
                                Map<String, Object> uploadresult = gtyUtil.getUploadFilePath(xzqdm);
                                LogUtil.logToTxt("获取上传路径结果：" + uploadresult, logUrl);

                                if (uploadresult.get("code").equals(200) && dbfile.exists()) {
                                    String writeurl = uploadresult.get("writeurl").toString();
                                    String readurl = uploadresult.get("readurl").toString();
                                    String contenttype = uploadresult.get("contenttype").toString();
                                    boolean flag = gtyUtil.uploadObject(writeurl, dbPath, contenttype);
                                    LogUtil.logToTxt("文件上传结果：" + flag, logUrl);
                                    if (flag) //上传成功
                                    {
                                        obj.put("url", readurl);
                                        obj.put("password", dbPass);
                                        obj.replace("code", "WPZFNDTB2024_RECV");
                                        //05 上传成功 提交成果
                                        Map<String, Object> pushresult = gtyUtil.pushDataPackage(obj.toString());
                                        LogUtil.logToTxt("DB包提交结果：" + pushresult, logUrl);
                                        if (pushresult.get("code").equals(200)) {
                                            Map<String, Object> map2 = new HashMap<>();
                                            map2.put("xzqdm", xzqdm);
                                            map2.put("submitstatus", "1");
                                            String submittime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime());
                                            map2.put("submittime", submittime);
                                            wpzfDockGxServiceImpl.updateQualitytestingBySubmitStatus(map2);

                                            Map<String, Object> map = new HashMap<>();
                                            map.put("jobid", pushresult.get("message") + "");
                                            map.put("xzqdm", xzqdm);
                                            wpzfDockServiceImpl.updateQualitytestingToJobid(map);
                                        } else {
                                            return AjaxResult.error("DB包提交失败," + pushresult.get("message").toString());
                                        }
                                    } else {
                                        return AjaxResult.error("文件上传到国土云OBS桶失败");
                                    }
                                } else {
                                    return AjaxResult.error("获取上传路径地址失败");
                                }
                            } else {
                                return AjaxResult.error("DB质检未通过,无法提交", rest);
                            }
                        } else {
                            return AjaxResult.error("数据正在质检 暂无法提交");
                        }
                    } else //有更新
                    {
                        return AjaxResult.error("数据有更新 正在打包中 暂无法提交");
                    }
                } else {
                    return AjaxResult.error("未获取该行政区打包质检记录数据");
                }
            }
            return AjaxResult.success("DB包提交成功");
        } else {
            LogUtil.logToTxt("无当前省份权限，用户行政区代码：" + user_xzqdm + "，行政区代码：" + xzqdm, logUrl);
            return AjaxResult.error("无当前省份权限");
        }
    }

    @RequestMapping(value = "/pushDBList", method = RequestMethod.POST)
    public AjaxResult pushDBList(@RequestBody Map<String, Object> param) throws IOException {
        String xzqdm = param.get("xzqdm") + "";
        String savePath = System.getProperty("user.dir") + "\\" + "pushDBFile";
        File folder = new File(savePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //从表中获取
        List<Map<String, Object>> restList = wpzfDockGxServiceImpl.queryAllQualitytestingByXzqdm(param);
        for (Map<String, Object> rest : restList) {
            LogUtil.logToTxt(xzqdm + "打包质检结果：" + rest, logUrl);
            if (rest != null) {
                if (rest.get("dburl") == null || rest.get("dburl").toString() == "") {
                    return AjaxResult.error("该区县DB包暂未打包，无法提交");
                }
                String dbPath = rest.get("dburl").toString();
                String dbPass = rest.get("dbpassword").toString();
                String status = rest.get("status").toString();//已质检状态
                String updatestatus = rest.get("updatestatus").toString();//更新状态
                String submitstatus = rest.get("submitstatus").toString();//提交状态
                xzqdm = rest.get("xzqdm").toString();


                if (("0").equals(updatestatus))  //无更新
                {
                    if (("2").equals(status)) //已质检
                    {
                        if (!Objects.equals(rest.get("signurl").toString(), "") && rest.get("signurl") != null) //质检通过 产生签章
                        {
                            String fileName = dbPath.substring(dbPath.lastIndexOf("/") + 1);
                            dbPath = downloadByIO(dbPath, savePath, fileName);
                            File dbfile = new File(dbPath);

                            String signpath = rest.get("signurl").toString();
                            fileName = signpath.substring(signpath.lastIndexOf("/") + 1);
                            signpath = downloadByIO(signpath, savePath, fileName);
                            String fileContent = "";
                            File signfile = new File(signpath);
                            if (signfile.exists()) {
                                LogUtil.logToTxt("签章下载成功", logUrl);
                                fileContent = readFileAsString(signpath);
                            }

                            JSONObject obj = JSON.parseObject(fileContent);
                            //获取到上传路径
                            Map<String, Object> uploadresult = gtyUtil.getUploadFilePath(xzqdm);
                            LogUtil.logToTxt("获取上传路径结果：" + uploadresult, logUrl);

                            if (uploadresult.get("code").equals(200) && dbfile.exists()) {
                                String writeurl = uploadresult.get("writeurl").toString();
                                String readurl = uploadresult.get("readurl").toString();
                                String contenttype = uploadresult.get("contenttype").toString();
                                boolean flag = gtyUtil.uploadObject(writeurl, dbPath, contenttype);
                                LogUtil.logToTxt("文件上传结果：" + flag, logUrl);
                                if (flag) //上传成功
                                {
                                    obj.put("url", readurl);
                                    obj.put("password", dbPass);
                                    obj.replace("code", "WPZFNDTB2024_RECV");
                                    //05 上传成功 提交成果
                                    Map<String, Object> pushresult = gtyUtil.pushDataPackage(obj.toString());
                                    LogUtil.logToTxt("DB包提交结果：" + pushresult, logUrl);
                                    if (pushresult.get("code").equals(200)) {
                                        Map<String, Object> map2 = new HashMap<>();
                                        map2.put("xzqdm", xzqdm);
                                        map2.put("submitstatus", "1");
                                        String submittime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime());
                                        map2.put("submittime", submittime);
                                        wpzfDockGxServiceImpl.updateQualitytestingBySubmitStatus(map2);

                                        Map<String, Object> map = new HashMap<>();
                                        map.put("jobid", pushresult.get("message") + "");
                                        map.put("xzqdm", xzqdm);
                                        wpzfDockServiceImpl.updateQualitytestingToJobid(map);
                                    } else {
                                        return AjaxResult.error("DB包提交失败," + pushresult.get("message").toString());
                                    }
                                } else {
                                    return AjaxResult.error("文件上传到国土云OBS桶失败");
                                }
                            } else {
                                return AjaxResult.error("获取上传路径地址失败");
                            }
                        } else {
                            return AjaxResult.error("DB质检未通过,无法提交", rest);
                        }
                    } else {
                        return AjaxResult.error("数据正在质检 暂无法提交");
                    }
                } else //有更新
                {
                    return AjaxResult.error("数据有更新 正在打包中 暂无法提交");
                }
            } else {
                return AjaxResult.error("未获取该行政区打包质检记录数据");
            }
        }
        return AjaxResult.success("DB包提交成功");
    }

    public static String downloadByIO(String url, String saveDir, String fileName) {
        BufferedOutputStream bos = null;
        InputStream is = null;
        try {
            byte[] buff = new byte[8192];
            is = new URL(url).openStream();
            File file = new File(saveDir, fileName);
            file.getParentFile().mkdirs();
            bos = new BufferedOutputStream(new FileOutputStream(file));
            int count = 0;
            while ((count = is.read(buff)) != -1) {
                bos.write(buff, 0, count);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return saveDir + "\\" + fileName;
    }

    public static String readFileAsString(String filePath) {
        StringBuilder contentBuilder = new StringBuilder();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                contentBuilder.append(line).append(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        return contentBuilder.toString();
    }


}
